package fourmiefight.metier;

import java.util.Observable;
import java.util.Timer;
import java.util.TimerTask;

public class UpdateTimer extends Observable
{
	public static final double NANO_TO_BASE = 1.0e9;
	private static final int NORMAL_REFRESH_RATE = 30;
	
	private long last;
	private double elapsedTime;
	private int velocity;
	private Timer timer;
	
	public UpdateTimer() 
	{
		velocity = 1;
	}
	
	public void start() 
    {
		timer = new Timer();
        this.last = System.nanoTime();
        TimerTask task = new TimerTask() 
        {
			@Override
			public void run() 
			{
				loop();
			}
		};
        timer.schedule(task, 0, NORMAL_REFRESH_RATE);
    }
	
	public void loop()
	{
	    long time = System.nanoTime();
	    long diff = time - this.last;
	    this.last = time;
	    elapsedTime = (double) diff / NANO_TO_BASE * velocity;
	    this.setChanged();
	    this.notifyObservers();
	}

	public double getElapsedTime() 
	{
		return elapsedTime;
	}
	
	public void setVelocity(int vel)
	{
		this.velocity = vel;
	}
	
	public int getVelocity()
	{
		return velocity;
	}
	
	public void resetTimer()
	{
        timer.cancel();
	}
}
